<template>
    <div class="table-main">
        <el-form
            ref="section_head"
            :inline="true"
            size="small"
            style="margin-bottom: -18px display: flex justify-content: space-between"
        >
            <el-form-item label="部门名称" prop="query">
                <el-input v-model="query" placeholder="部门名称" />
            </el-form-item>
            <el-form-item>
                <el-button round icon="el-icon-refresh-left" @click="query = ''"
                    >重置</el-button
                >
            </el-form-item>
            <el-form-item>
                <el-button
                    type="warning"
                    icon="el-icon-sort"
                    @click="contraction"
                    >展开/折叠</el-button
                >
            </el-form-item>
        </el-form>
        <el-table
            ref="treeTable"
            row-key="id"
            :data="treeTable"
            default-expand-all
            class="sec_table"
            style="width: 100%margin-bottom: 20px"
            :expand-row-keys="expandRow"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
            <el-table-column prop="name" label="部门名称" />
            <el-table-column prop="principal" label="主要负责人" />
            <el-table-column prop="date" label="创建日期" />
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                        v-show="scope.row.parent_id != null"
                        size="mini"
                        round
                        type="success"
                        class="el-icon-edit"
                        @click="handleEdit(scope.$index, scope.row)"
                    />
                    <el-button
                        size="mini"
                        round
                        type="primary"
                        class="el-icon-plus"
                        :style="{
                            margin: scope.row.parent_id == null ? '0px' : ''
                        }"
                        @click="handleAdd(scope.$index, scope.row)"
                    />
                    <el-button
                        v-show="scope.row.parent_id != null"
                        size="mini"
                        round
                        type="danger"
                        class="el-icon-delete"
                        @click="handleDelete(scope.$index, scope.row)"
                    />
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑添加框 -->
        <el-dialog
            :title="dialogType == 'add' ? '添加部门信息' : '编辑部门信息'"
            :visible.sync="editDialog"
            width="500px"
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="100px"
                size="medium"
                style="width:400px"
            >
                <el-form-item label="上级部门：" prop="parent_name">
                    <el-input v-model.trim="form.parent_name" readonly />
                </el-form-item>
                <el-form-item label="部门名称：" prop="name">
                    <el-input v-model.trim="form.name" />
                </el-form-item>
                <el-form-item label="主要负责人：" prop="principal">
                    <el-input v-model.trim="form.principal" />
                </el-form-item>
                <el-form-item label="创建日期：" prop="date">
                    <el-date-picker
                        v-model="form.date"
                        type="date"
                        placeholder="选择日期"
                        :picker-options="pickerOptions"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd"
                    />
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input v-model.trim="form.remark" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        :loading="loadingbut"
                        @click="handleSave('form')"
                        >{{ loadingbuttext }}</el-button
                    >
                    <el-button @click="resetForm()">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
const defaultForm = {
    id: "",
    parent_id: "",
    parent_name: "",
    name: "",
    date: "",
    principal: "",
    remark: ""
};
const defaultMsg = {
    id: "",
    parent_id: "",
    name: "",
    date: "",
    principal: "",
    remark: ""
};
// 从工具库里面拿防抖方法
// import { debounce } from 'Lodash'
export default {
    name: "SectionP",
    data() {
        // 检测汉字正则
        const reChina = new RegExp("[\u4e00-\u9fa5]$");
        // 验证部门名称
        const NameValidator = (rule, value, callback) => {
            if (reChina.test(value)) {
                callback();
            } else {
                callback(new Error("请输入中文名称"));
            }
        };
        // 验证负责人名字
        const realnameReg = new RegExp(/^([a-zA-Z0-9\u4e00-\u9fa5\·]{1,10})$/);
        const PrincipalValidator = (rule, value, callback) => {
            console.log(value);
            if (realnameReg.test(value)) {
                callback();
            } else {
                return callback(
                    new Error("您的真实姓名格式错误,请输入英文或汉字!")
                );
            }
        };
        return {
            // 表单验证
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入部门名称",
                        trigger: "blur",
                        validator: NameValidator
                    },
                    {
                        min: 3,
                        max: 5,
                        message: "长度在 3 到 5 个字符",
                        trigger: "blur"
                    }
                ],
                principal: [
                    {
                        message: "请输入负责人姓名",
                        trigger: "blur",
                        validator: PrincipalValidator
                    }
                ],
                remark: [
                    // 非必填项
                    { message: "请输入部门备注", trigger: "blur" }
                ]
            },
            // 表单数据
            form: Object.assign({}, defaultForm),
            // 状态是否禁用
            isDisabled: false,
            // 弹出框类型
            dialogType: "",
            editDialog: false,
            // 数据
            tableData: [],
            // 是否折叠
            showStyle: true,
            // 搜索的数据
            query: "",
            expandRow: [],
            list: [
                {
                    parent_id: null,
                    id: 1,
                    date: "2020-11-25",
                    name: "杭州某某科技有限公司",
                    principal: "马某",
                    remark: ""
                },
                {
                    parent_id: 1,
                    id: 2,
                    date: "2020-12-01",
                    name: "研发部",
                    principal: "张某",
                    remark: ""
                },
                {
                    parent_id: 1,
                    id: 3,
                    date: "2020-12-01",
                    name: "测试部",
                    principal: "王某",
                    remark: ""
                },
                {
                    parent_id: 2,
                    id: 4,
                    date: "2020-12-05",
                    name: "UI部",
                    principal: "付某",
                    remark: ""
                },
                {
                    parent_id: 2,
                    id: 5,
                    date: "2020-12-01",
                    name: "运维部",
                    principal: "曾某",
                    remark: ""
                },
                {
                    parent_id: 1,
                    id: 6,
                    date: "2020-12-01",
                    name: "人力资源部",
                    principal: "张某",
                    remark: ""
                }
            ],
            // 保存数据
            msg: "",
            // 得到父级创建的时间
            parent_date: "",
            // 加一个业务判断需求就是部门创建时间不能比父级部门创建时间早
            pickerOptions: {},
            // 按钮加载效果
            loadingbut: false, // 审核提交加载中
            loadingbuttext: "确定"
        };
    },
    computed: {
        treeTable() {
            // 搜索的值
            const searchValue = this.query.toString().trim();
            if (searchValue) {
                const treeData = this.tableData;
                // 得到过滤后的数据
                const handleTreeData = this.handleTreeData(
                    treeData,
                    searchValue
                );
                this.setExpandRow(handleTreeData);
                this.expandRow = this.expandRow.join(",").split(",");
                return handleTreeData;
            }
            return this.tableData;
        }
    },
    watch: {
        editDialog(v) {
            if (v === false) {
                // 重置验证
                this.$refs["form"].resetFields();
                // 初始化
                this.form = Object.assign({}, defaultForm);
            }
        },
        parent_date(v) {
            // this.pickerOptions.disabledDate = disabledDate(time) {
            //   console.log(parent_date);
            //   console.log(Date.now());
            //   return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
            // }
        }
    },
    created() {
        // 本地存储为空的时候
        if (!JSON.parse(localStorage.getItem("table2"))) {
            localStorage.setItem("table2", JSON.stringify(this.list));
        }
        this.list = JSON.parse(localStorage.getItem("table2"));
        this.tableData = this.req_data(this.list);
    },
    methods: {
        req_data(arr) {
            // 从后端请求来的数据
            const s = arr.map(v => {
                let name = "";
                arr.forEach(l => {
                    if (v.parent_id == l.id) {
                        name = l.name;
                    }
                });
                if (name) {
                    v.parent_name = name;
                } else {
                    v.parent_name = v.name;
                }
                return v;
            });
            return this.recursion(s);
        },
        // 递归数据
        recursion(arr) {
            function fn(temp) {
                const result = [];
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].parent_id == temp) {
                        result.push(arr[i]);
                        arr[i].children = fn(arr[i].id);
                    }
                }
                return result;
            }
            return fn(null);
        },
        // 点击编辑
        handleEdit(index, row) {
            this.dialogType = "edit";
            this.form = { ...row };
            this.msg = { ...this.form };
            this.editDialog = true;
        },
        // 点击删除按钮
        handleDelete(index, row) {
            // 当子集为空时才可以删除
            if (row.children == null || row.children.length == 0) {
                // 二次确认是否删除
                this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    const data = JSON.parse(localStorage.getItem("table2"));
                    // 找到索引    findIndex满足这个函数则返回数组索引
                    const index = data.findIndex(data => data.id === row.id);
                    console.log(index);
                    // 删除对应的值   splice  删除序号为index的一个值
                    data.splice(index, 1);
                    // 重新渲染一遍数据
                    this.tableData = this.req_data(data);
                    // 再存储一遍数据
                    localStorage.setItem("table2", JSON.stringify(data));
                    this.$message({
                        type: "success",
                        message: "删除成功!"
                    });
                });
            } else {
                this.$message.closeAll();
                this.$message({
                    message: "此部门下面还有子部门不能删除！",
                    type: "warning"
                });
            }
        },
        // 添加部门信息
        handleAdd(index, row) {
            this.dialogType = "add";
            // 禁用状态不能添加部门
            this.form.parent_name = row.name;
            this.form.parent_id = row.id;
            this.form.id = this.createRandomId();
            // 得到父级节点的日期
            this.parent_date = row.date;
            this.msg = { ...this.form };
            // 判断禁用状态不能添加部门
            if (
                (row == undefined && this.tableData[0].status != 0) ||
                row.status != 0
            ) {
                this.editDialog = true;
            } else {
                this.$message({
                    type: "warning",
                    message: "禁用状态不能添加部门!"
                });
            }
        },
        // 点击保存数据
        handleSave(formName) {
            this.loadingbut = true;
            this.loadingbuttext = "请稍后...";
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.msg = Object.assign({}, defaultMsg);
                    for (const ops in this.msg) {
                        this.msg[ops] = this.form[ops];
                    }
                    if (this.dialogType === "add") {
                        this.list.push(this.msg);
                        console.log(this.list);
                        // 重新渲染一遍数据
                        this.tableData = this.req_data(this.list);
                        // 把数据添加到本地存储
                        localStorage.setItem(
                            "table2",
                            JSON.stringify(this.list)
                        );
                        setTimeout(() => {
                            this.loadingbut = false;
                            this.loadingbuttext = "确定";
                            this.editDialog = false;
                            this.$message({
                                type: "success",
                                message: "部门添加成功!"
                            });
                        }, 3000);
                    } else {
                        // 得到所有数据
                        const data = JSON.parse(localStorage.getItem("table2"));
                        const result = data.map(v => {
                            // 找到修改的值并赋值
                            if (v.id === this.msg.id) {
                                v = this.msg;
                            }
                            return v;
                        });
                        // 重新渲染一遍数据
                        this.tableData = this.req_data(result);
                        // 再存储一遍数据
                        localStorage.setItem("table2", JSON.stringify(result));
                        // 来个交互体验
                        setTimeout(() => {
                            this.loadingbut = false;
                            this.loadingbuttext = "确定";
                            this.editDialog = false;
                            this.$message({
                                type: "success",
                                message: "部门修改成功!"
                            });
                        }, 3000);
                    }
                } else {
                    return false;
                }
            });
        },
        // 限制日期函数
        limitDate() {},
        // 重置数据
        resetForm() {
            this.form = { ...this.msg };
        },
        //  树形表格过滤
        handleTreeData(treeData, searchValue) {
            // 判断数据是否为空
            if (!treeData || treeData.length === 0) {
                return [];
            }
            const array = [];
            for (let i = 0; i < treeData.length; i += 1) {
                let match = false;
                for (const pro in treeData[i]) {
                    if (typeof treeData[i][pro] === "string") {
                        match |= treeData[i][pro].includes(searchValue);
                        // match =match| treeData[i][pro].includes(searchValue)
                        if (match) break;
                    }
                }
                // 判断是否需要继续递归
                if (
                    this.handleTreeData(treeData[i].children, searchValue)
                        .length > 0 ||
                    match
                ) {
                    array.push({
                        ...treeData[i],
                        children: this.handleTreeData(
                            treeData[i].children,
                            searchValue
                        )
                    });
                }
            }
            return array;
        },
        // 将过滤好的树形数据展开
        setExpandRow(handleTreeData) {
            if (handleTreeData.length) {
                for (const i of handleTreeData) {
                    this.expandRow.push(i.id);
                    if (i.children.length) {
                        this.setExpandRow(i.children);
                    }
                }
            }
        },
        // 展开折叠
        contraction(val) {
            if (this.showStyle) {
                this.showStyle = false;
                if (this.tableData.length != 0) {
                    const elsopen = this.$el.getElementsByClassName(
                        "el-table__expand-icon--expanded"
                    );
                    if (
                        this.$el.getElementsByClassName(
                            "el-table__expand-icon--expanded"
                        )
                    ) {
                        for (let i = 0; i < elsopen.length; i++) {
                            elsopen[i].click();
                        }
                    }
                }
            } else {
                this.showStyle = true;
                const els = document.getElementsByClassName(
                    "el-table__expand-icon"
                );
                if (this.tableData.length != 0 && els.length != 0) {
                    for (let j1 = 0; j1 < els.length; j1++) {
                        els[j1].classList.add("dafult");
                    }
                    if (
                        this.$el.getElementsByClassName(
                            "el-table__expand-icon--expanded"
                        )
                    ) {
                        const open = this.$el.getElementsByClassName(
                            "el-table__expand-icon--expanded"
                        );
                        for (let j = 0; j < open.length; j++) {
                            open[j].classList.remove("dafult");
                        }
                        const dafult = this.$el.getElementsByClassName(
                            "dafult"
                        );
                        for (let a = 0; a < dafult.length; a++) {
                            dafult[a].click();
                        }
                    }
                }
            }
        },
        // 随机生成不重复的ID
        createRandomId() {
            return (
                (Math.random() * 10000000).toString(16).substr(0, 4) +
                "-" +
                new Date().getTime() +
                "-" +
                Math.random()
                    .toString()
                    .substr(2, 5)
            );
        }
    }
};
</script>
<style>
.sec_table .cell .el-table__expand-icon {
    margin: 0px;
}
</style>
